package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Bright
 * @since 2022-04-09
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
    }

    @Override
    public List<ExcelDictDTO> listData() {
        List<Dict> dicts = baseMapper.selectList(null);
        ArrayList<ExcelDictDTO> excelDictDTOS = new ArrayList<>();
        dicts.forEach(dict -> {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict, excelDictDTO);
            excelDictDTOS.add(excelDictDTO);
        });
        return excelDictDTOS;
    }

    @Override
    public List<Dict> getByParentId(Long parentId) {

        List<Dict> dicts = null;
        try {
            dicts = (List<Dict>) redisTemplate.opsForValue().get("dictList:" + parentId);
            log.info("查询redis key:" + "dictList:" + parentId);
        } catch (Exception e) {
            log.error("服务器没有启动" + ExceptionUtils.getStackTrace(e));
        }

        if (dicts == null) {
            log.info("从数据库中获取数据列表");
            QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
            dictQueryWrapper.eq("parent_id", parentId);
            dicts = baseMapper.selectList(dictQueryWrapper);
            dicts.forEach(dict -> dict.setHasChildren(hasChildren(dict.getId())));

            try {
                redisTemplate.opsForValue().set("dictList:" + parentId, dicts, 5, TimeUnit.MINUTES);
                log.info("存入redis key:" + "dictList:" + parentId);
            } catch (Exception e) {
                log.error("服务器没有启动" + ExceptionUtils.getStackTrace(e));
            }

        }
        return dicts;
    }

    @Override
    public Boolean hasChildren(Long id) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(dictQueryWrapper);
        if (count > 0) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        return this.getByParentId(dict.getId());
    }

    @Override
    public String getDictNamebyValueAndDictCode(Integer value, String dictCode) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.select("id").eq("dict_code",dictCode);
        List<Object> objects = baseMapper.selectObjs(dictQueryWrapper);


        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper
                .select("name")
                .eq("parent_id", objects.get(0))
                .eq("value", value);
        List<Object> names = baseMapper.selectObjs(dictQueryWrapper);
        return (String) names.get(0);
    }


}
